package pers.lws.erp.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author liuws
 * @create 2020-09-03 15:18
 */
@Configuration
public class ShiroConfig {

    /**
     * 加密类型
     */
    private final String PASS_TYPE = "MD5";
    /**
     * 散列次数
     */
    private final Integer HASH_NUMBER = 1024;

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        //map.put("/sys/test", "roles[superAdmin2]");
        map.put("/**", "anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setUnauthorizedUrl("/sys/unauth");

        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    @Bean
    public Realm getRealm() {
        //自定义realm对象
        LoginUserRealm userRealm = new LoginUserRealm();
        //凭证匹配器
        HashedCredentialsMatcher hashMatcher = new HashedCredentialsMatcher(PASS_TYPE);
        //散列次数
        hashMatcher.setHashIterations(HASH_NUMBER);
        //使用凭证匹配
        userRealm.setCredentialsMatcher(hashMatcher);
        return userRealm;
    }
}
